"""
演示对文件的读取
"""
import time

#打开文件
# f = open("/pycode/黑马程序员/基础/5.列表.py", "r", encoding="UTF-8")#
# print(type(f))

#读取文件 -read()
# print(f"读取10个字节的结果是: {f.read(10)}")
# print(f"read读取全部内容的结果是: {f.read()}")

#读取文件 -readlines()
# lines = f.readlines()
# print(f"lines的对象类型是: {type(lines)}")
# print(f"lines对象的内容是: {lines}")

#读取文件 -readline()
# line1 = f.readline()
# line2 = f.readline()
# line3 = f.readline()
# print(f"第一行数据是: {line1}")
# print(f"第二行数据是: {line2}")
# print(f"第三行数据是: {line3}")
#
# # for循环读取文件行
# for line in f:
#     print(f"每一行数据是: {line}")

# time.sleep(50000)

#关闭文件  -close()
# f.close()
#
# time.sleep(50000)

#with open 语法操作文件
# with open("5.列表.py", "r", encoding="UTF-8") as f:
#     for line in f:
#         print(f"每一行的数据是: {line}")
#
# time.sleep(5000)
"""
读取文件,统计单词次数
"""
#方法1:一行一行读取
with open("C:/Users/86131/Desktop/测试.txt","r",encoding="UTF-8") as f:
    i = 0
    for line in f:
        #需要首先先去除收尾的空格和换行符
        line = line.strip()
        line_list = line.split(" ")

        print(f"每一行的内容: {line_list}")
        for word in line_list:
            if word == "12345":
                i += 1

    print(f"文件出现12345的次数有: {i}次")

#方法2:读取文件全部内容,通过字符串count方法进行统计
f = open("C:/Users/86131/Desktop/测试.txt","r",encoding="UTF-8")
content = f.read()
count = content.count("12345")
print(f"12345在文件中出现了: {count}次")